﻿using AuSys.Services.App.FileStorage.Specific;
using AuSys.Utils.Reflection;

namespace AuSys.Services.App.FileStorage
{
    public static class FileStorageSetup
    {
        public static IServiceCollection SetupFileStorage(
            this IServiceCollection services, IConfiguration c)
        {
            var type = c[fileStorageConfigTypeKey]?.ToLower();
            if (string.IsNullOrWhiteSpace(type))
                throw new Exception($"缺少配置项<{fileStorageConfigTypeKey}>");
            if (type == "local")
            {
                var cfg = ReadFlatConfiguration<LocalStorageConfig>(
                    c, localStorageConfigKey, [nameof(LocalStorageConfig.DomainName)]);
                var storage = new LocalStorage(cfg);
                services.AddSingleton<IFileStorage>(storage);
            }
            else if (type == "aliyunoss")
            {
                var cfg = ReadFlatConfiguration<AliyunOssStorageConfig>(
                    c, aliyunOssStorageConfigKey, []);
                var storage = new AliyunOssStorage(cfg);
                services.AddSingleton<IFileStorage>(storage);
            }
            else if (type == "noneed") { }
            else
                throw new Exception($"不支持的配置项值<{fileStorageConfigTypeKey}>的“{type}”");
            return services;
        }

        private static T ReadFlatConfiguration<T>(
            IConfiguration config, string key, List<string> skipCheckProps) where T : new()
        {
            T res = new();
            config.GetSection(key).Bind(res);
            if (!PropCheckHelper.AllStringPropertiesNotEmpty(res, out var invalidProp, skipCheckProps))
                throw new Exception($"缺少配置项<{key}:{invalidProp}>");
            return res;
        }

        private const string fileStorageConfigRootKey = "FileStorage";
        private const string fileStorageConfigTypeKey = $"{fileStorageConfigRootKey}:Type";
        private const string localStorageConfigKey = $"{fileStorageConfigRootKey}:Local";
        private const string aliyunOssStorageConfigKey = $"{fileStorageConfigRootKey}:AliyunOss";
    }

    public static class FileStorageConsts
    {
        public const string ActionRoutePattern 
            = $"{ActionRoutePatternBase}/{ActionRoutePatternSlot}";
        public const string ActionRoutePatternBase = "/f";
        public const string ActionRoutePatternSlot = "{filename}";
        public static string ActionRouteOf(string pathName)
            => $"{ActionRoutePatternBase}/{pathName}";
    }
}
